package com.shuqi.sdk.ad;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Handler;
import android.text.TextUtils;
import cn.domob.android.ads.DomobSplashAd;
import cn.domob.android.ads.DomobSplashAd.DomobSplashMode;
import cn.domob.android.ads.DomobSplashAdListener;

import com.shuqi.common.Config;
import com.shuqi.common.LoadingImg;
import com.shuqi.common.utils.Log4an;
import com.shuqi.common.utils.SharedPreferenceUtil;
import com.shuqi.controller.Loading;
import com.shuqi.controller.R;
import com.shuqi.statistics.StatisticsEventID;
import com.shuqi.statistics.StatisticsUtils;

/**
 * 开屏广告
 * 
 * @author Jianda.Yang
 * 
 * @Date 2014-5-6 下午3:05:37
 */
public class ADViewLoading {
    private final static String logTag = "ADViewLoading";

    /** 是否开启开屏广告(仅作打包时修改：true-->开启开屏广告;false-->关闭开屏广告) */
    public static final boolean isOpenADViewLoading = true;

    private static final String SHAREDPREFERENCE_NAME = "checkad5";

    private static DomobSplashAd splashAd;

    private static ADViewLoading adViewLoading;
    private static LoadingADLinstener mlinstener;
    private static boolean isLoading = false;
    private static Activity context;


    private ADViewLoading(Loading activity) {
        context = activity;
        if (isShowAd(activity)) {
            initAdView(activity);
        }
    }

    public static ADViewLoading getInstance(Loading activity, LoadingADLinstener linstener) {
        isLoading = true;
        if (adViewLoading == null) {
            initAd();
            adViewLoading = new ADViewLoading(activity);
            mlinstener = linstener;
        }
        return adViewLoading;
    }

    private static String ratio;
    private static String content;

    /**
     * 判断是否需要显示开屏广告：受封面页广告Domob的状态的控制：位置是16
     * 
     * @param activity
     * @return
     */
    public static boolean isShowAd(Loading activity) {
        try {
            SharedPreferences sp2 =
                    activity.getSharedPreferences(SHAREDPREFERENCE_NAME, Context.MODE_PRIVATE);
            ratio = sp2.getString("which", null);
            Log4an.d(logTag, "ratio=" + ratio);
            if (TextUtils.isEmpty(ratio)) {
                return false;
            }
            // 取封面页的广告显示数据
            Log4an.d(logTag, "开屏广告：" + (sp2.getBoolean("isshowad", false) ? "开启" : "关闭") + ", 比率串："
                    + ratio);
            if ((sp2.getBoolean("isshowad", false)) && !TextUtils.isEmpty(ratio)) {
                String[] state = ratio.split(":");
                Log4an.d(logTag, "state.length=" + state.length);
                for (int i = 0; i < state.length; i++) {
                    if (!"0".equals(state[i])) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log4an.d(logTag, "不显示开屏广告");
        return false;// 应该返回false
    }

    /** 当前显示广告的序号 */
    private static int whichAd;

    /** 初始化广告参数 */
    private static void initAd() {
        try {
            String bz = ratio;
            Log4an.d(logTag, "bz=" + bz);
            float rate[] = null;
            if ("".equals(bz)) {
                whichAd = -1;
            } else {
                if (bz.endsWith(":")) {
                    bz = bz.substring(0, bz.length() - 1);
                }
                List<Float> bzList = new ArrayList<Float>();
                int index = 0;
                int index2 = 0;
                while (true) {
                    index = bz.indexOf(":", index2);
                    if (index == -1) {
                        try {
                            bzList.add(Float.valueOf(bz.substring(index2)));
                        } catch (NumberFormatException e) {
                            bzList.add(1f);
                            e.printStackTrace();
                        }
                        break;
                    } else {
                        try {
                            bzList.add(Float.valueOf(bz.substring(index2, index)));
                        } catch (NumberFormatException e) {
                            bzList.add(1f);
                            e.printStackTrace();
                        }
                    }
                    index2 = index + 1;
                }
                rate = new float[bzList.size()];
                float num = 0;
                for (float f : bzList) {
                    num += f;
                }
                for (int i = 0; i < bzList.size(); i++) {
                    rate[i] = bzList.get(i) / num * 10000;
                }
                int ran = new Random().nextInt(10000) + 1;
                num = 0;
                for (int i = 0; i < rate.length; i++) {
                    num += rate[i];
                    if (ran <= num) {
                        Log4an.e(logTag, "open load i=" + i);
                        whichAd = i;
                        Log4an.d(logTag,
                                "open load whichAd=" + whichAd + ",local=" + bzList.get(whichAd));
                        break;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化广告视图
     * 
     * @param activity
     */
    public void initAdView(final Loading activity) {
        Log4an.e(logTag, "---------initAdView() whichAd=" + whichAd);
        switch (whichAd) {
            case 11:// 多盟广告
                showAD_Domob(activity);
                break;
            case 38:// 自主开屏1
            case 39:// 自主开屏2
                showSQ_OpenAD(activity);
                break;
            default:
                Log4an.e(logTag, "default run handler postDelayed");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mlinstener.onSplashEnd();
                        isLoading = false;
                    }
                }, 1);
                break;
        }
    }

    /**
     * 添加多盟广告
     * 
     * @param activity
     */
    private void showAD_Domob(final Activity activity) {
        // * DomobSplashMode.DomobSplashModeFullScreen 请求开屏广告的尺寸为全屏
        // * DomobSplashMode.DomobSplashModeSmallEmbed 请求开屏广告的尺寸不是全屏，根据设备分辨率计算出合适的小屏尺寸
        // * DomobSplashMode.DomobSplashModeBigEmbed
        // 请求开屏广告的尺寸不是全屏，更具设备分辨率计算出合适的相对SmallMode的尺寸
        splashAd =
                new DomobSplashAd(activity, "56OJyMmIuMG49V/uFo", "16TLweKoAchs2NU-9PFNr3Qs",
                        DomobSplashMode.DomobSplashModeBigEmbed);

        // splashAd.setSplashTopMargin(200);非全屏时设置
        splashAd.setSplashAdListener(new DomobSplashAdListener() {
            @Override
            public void onSplashPresent() {
                Log4an.d(logTag, "onSplash_Present");
            }

            @Override
            public void onSplashDismiss() {
                Log4an.d(logTag, "onSplash_Dismiss");
                // 开屏回调被关闭时，立即进行界面跳转，从开屏界面到主界面。
                mlinstener.onSplashEnd();
                isLoading = false;
                // splashAd.closeSplash();如果应用没有单独的闪屏Activity，需要调用closeSplash方法去关闭开屏广告
            }

            @Override
            public void onSplashLoadFailed() {
                Log4an.d(logTag, "onSplashLoad_Failed");
                mlinstener.onSplashEnd();
                isLoading = false;
            }
        });
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                Log4an.d(
                        logTag,
                        "splashAd==" + (splashAd == null) + ",isSplashAdReady="
                                + splashAd.isSplashAdReady() + ",activity=" + (activity == null)
                                + ",finish=" + activity.isFinishing());
                if (splashAd != null && splashAd.isSplashAdReady() && activity != null
                        && !activity.isFinishing()) {
                    Log4an.d(logTag, "开屏广告准备好了，开始展示");
                    splashAd.splash(activity, activity.findViewById(R.id.loading_ad_splash));
                } else if (mlinstener != null) {
                    Log4an.d(logTag, "开屏广告未缓存，跳过");
                    mlinstener.onSplashEnd();
                    isLoading = false;
                } else {
                    Log4an.d(logTag, "1.error splashAd or activity or mlinstener isNull");
                }
            }
        }, 1);
    }

    /**
     * 自主开屏广告
     * 
     * @param activity
     */
    private void showSQ_OpenAD(final Activity activity) {
        SharedPreferences sp2 =
                activity.getSharedPreferences(SHAREDPREFERENCE_NAME, Context.MODE_PRIVATE);
        String selfadid = sp2.getString("selfadids", null);
        String strIndex = null;
        if (!TextUtils.isEmpty(selfadid)) {
            String selfadis[] = selfadid.split(":");
            for (int i = 0; i < selfadis.length; i++) {
                if ((whichAd + 1) == Integer.valueOf(selfadis[i])) {
                    strIndex = selfadis[i];
                    break;
                }
            }
            Log4an.d(logTag, "selfadis.length=" + selfadis.length);
        }
        Log4an.d(logTag, "【addSQ_OpenAD】selfadid=" + selfadid);
        Log4an.d(logTag, "strIndex=" + strIndex);
        if (!TextUtils.isEmpty(strIndex)) {
            content = sp2.getString("selfadid" + strIndex + "content", null);
        } else {
            // content = sp2.getString("content", null);//此位置是0位置的自主banner广告，不打开此处
        }
        Log4an.d(logTag, "添加自主广告：" + content);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (!TextUtils.isEmpty(content)) {
                    String name =
                            content.substring(content.lastIndexOf("/") + 1,
                                    content.lastIndexOf("."));
                    File file = new File(Config.DEFAULT_PATH_LOADINADGPIC + name);
                    String spName =
                            context.getSharedPreferences(SharedPreferenceUtil.SP_NAME_CONFIG,
                                    Context.MODE_PRIVATE).getString(name, "");
                    if (activity != null && !activity.isFinishing() && file.exists()
                            && !TextUtils.isEmpty(spName)) {
                        Log4an.d(logTag, "自主开屏广告准备好了，开始展示");
                        mlinstener.onShowAd(context, name);
                        mlinstener.onSplashEnd();
                        isLoading = false;
                    } else if (mlinstener != null) {
                        Log4an.d(logTag, "自主开屏广告未缓存，跳过");
                        if (!TextUtils.isEmpty(content)) {
                            LoadingImg.downloadLoadingPic(context, content, name,
                                    Config.DEFAULT_PATH_LOADINADGPIC);
                            StatisticsUtils
                                    .onEvent(context, StatisticsEventID.AD_VIEW_LOADING_POST);
                            Log4an.d(logTag, "启动图开始下载..");
                        }
                        mlinstener.onSplashEnd();
                        isLoading = false;
                    } else {
                        Log4an.e(logTag, "2.error splashAd or activity or mlinstener isNull");
                    }
                } else {
                    if (mlinstener != null) {
                        Log4an.d(logTag, "自主开屏content is null ,直接跳过进入客户端");
                        mlinstener.onSplashEnd();
                    } else {
                        Log4an.e(logTag, "3.error splashAd or activity or mlinstener isNull");
                    }
                }
            }
        }, 1);
    }

    /***
     * 回收广告对象
     */
    public static void destoryAdView() {
        Log4an.d(logTag, "回收开屏广告资源 isLoading=" + isLoading);
        if (!isLoading) {
            splashAd = null;
            adViewLoading = null;
            mlinstener = null;
            Log4an.d(logTag, "回收开屏广告资源已完成");
        }
    }

    public interface LoadingADLinstener {
        public void onSplashEnd();

        public void onShowAd(Context context, String name);
    }
}
